package com.gnerv.cms.freemarker.tag;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gnerv.cms.dto.ArticleDTO;
import com.gnerv.cms.dto.ArticleDetailsDTO;
import com.gnerv.cms.dto.ArticleSearchDTO;
import com.gnerv.cms.freemarker.FreemarkerComponent;
import com.gnerv.cms.service.IArticleService;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * @author Gnerv LiGen
 * @description
 * @data 2019/4/3
 */
@FreemarkerComponent("g_article")
public class ArticleTagDirective implements TemplateDirectiveModel {

    @Resource
    private IArticleService articleService;

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
        Object catalogId = map.get("catalogId");
        Object articleId = map.get("articleId");
        Object child = map.get("child");
        Object size = map.get("size");
        if(!StringUtils.isEmpty(catalogId)){
            ArticleSearchDTO articleSearchDTO = new ArticleSearchDTO();
            if(StringUtils.isEmpty(child)){
                articleSearchDTO.setCatalogId(catalogId.toString());
            } else {
                articleSearchDTO.setCatalogId(null);
            }
            articleSearchDTO.setStatus(1);
            Page<ArticleDTO> articles = articleService.listArticle(articleSearchDTO, 1L, Long.valueOf(StringUtils.isEmpty(size) ? "30" : size.toString()));
            TemplateModel tm = builder.build().wrap(articles.getRecords());
            environment.setVariable("articles", tm);
        }else if(!StringUtils.isEmpty(articleId)){
            ArticleDetailsDTO articleDetails = articleService.selectArticleDetails(articleId.toString(), 1);
            TemplateModel tm = builder.build().wrap(articleDetails);
            environment.setVariable("article", tm);
        }
        templateDirectiveBody.render(environment.getOut());
    }

}
